﻿using System;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
using KPFramework.Demo.MainUi.Wnd;
using DevExpress.XtraBars;
using DevExpress.Mvvm;
using DevExpress.Utils;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraEditors;
using KPFramework.Base;
using KPFramework.Demo.Components;
using KPFramework.KUIFrame;
using KPFramework.Res.ResObject;

namespace KPFramework.Demo.MainUi
{
    internal partial class MainWnd : TabForm
    {
        public MainWnd()
        {
            InitializeComponent();
            _myComponentsCtrl = new HomePageCtrl(){Dock = DockStyle.Fill};
            pageHome.ContentContainer.Controls.Add(_myComponentsCtrl);
            
        }

        #region 属性

        private readonly HomePageCtrl _myComponentsCtrl = null;
        #endregion 


        #region 事件处理

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            DelegateCommand command = new DelegateCommand(() =>
            {
                //MessageBox.Show("Hello! I'm running!");
                //                var page = new TabFormPage();
                //                var ctrl = new  Comm.AppCenterCtrl(){Dock = DockStyle.Fill  };
                //                page.ContentContainer = new DevExpress.XtraBars.TabFormContentContainer(){Dock = DockStyle.Fill};
                //                page.ContentContainer.Controls.Add(ctrl);
                //                tabFormCtrl.Pages.Add(page);
                //               //tabFormControl1.LayoutChanged();
                tabFormControl1.SelectedPage = pageHome;
            });
            this.tabFormControl1.AddPageButton.BindCommand(command);
            //创建加载系统主页
            var homeUi= new HomePageUi(new KUIObject()
            {
                Name = "HOME",
                Title = "首页",
                Image = Properties.Resources.home_16x16
            });
            var ctrl = homeUi.CtrlOrCreate;
            ctrl.Dock = DockStyle.Fill;
            pageHome.ContentContainer = new TabFormContentContainer() { Dock = DockStyle.Fill };
            pageHome.ContentContainer.Controls.Add(ctrl);

            MainUi.CloseSplashScreen();
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            if (XtraMessageBox.Show("是否要退出系统?", "提示", MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question) != DialogResult.Yes)
            {
                e.Cancel = true;
                return;
            }
            base.OnClosing(e);

        }

        private void btnSysSet_ItemClick(object sender, ItemClickEventArgs e)
        {
            using (Wnd.SysSetWnd setWnd = new SysSetWnd())
            {
                setWnd.ShowDialog();
            }
        }


        private void btnBbs_ItemClick(object sender, ItemClickEventArgs e)
        {
            MainUi.StartUrl("http://www.ydljk.com/");
        }

        private void btnBook_ItemClick(object sender, ItemClickEventArgs e)
        {
            MainUi.StartUrl("http://www.teamdoc.ydljk.com/");
        }

        private void btnSet_ItemClick(object sender, ItemClickEventArgs e)
        {
           MainUi.SysSet();
        }
        private void btnSkinColor_ItemClick(object sender, ItemClickEventArgs e)
        {
            MainUi.SetSkinColor();
        }
        private void btnAbout_ItemClick(object sender, ItemClickEventArgs e)
        {
            MainUi.AboutSys();
        }
        private void btnGitee_ItemClick(object sender, ItemClickEventArgs e)
        {
            MainUi.StartUrl("https://gitee.com/KPlugin/MipDemo.git");
        }

        private void btnQqInfo_ItemClick(object sender, ItemClickEventArgs e)
        {
            var uiInfo = new QqInfoUi(new KUIObject()
            {
                Name = "QQ_INFO", 
                Title = "QQ群",
                Image = KPFramework.Demo.Properties.Resources.QQ
            });
            SetContent(uiInfo.UIObject);
        }
        #endregion


        #region 功能显示
        /// <summary>
        /// 获得当前显示的内容信息
        /// </summary>
        /// <returns></returns>
        public KUIObject GetCurrentContent()
        {
            var page = tabFormControl1.SelectedPage;
            IUIObject uiImpl = page?.Tag as IUIObject;
            return uiImpl?.UIObject;
        }

        /// <summary>
        /// 设置当前的内容信息
        /// </summary>
        /// <param name="uiObj"></param>
        public bool SetContent(KUIObject uiObj)
        {
            if (uiObj == null)
                return false;
            string strName = uiObj.Name;
            var pages = OnGetTab(strName);
            if (pages != null)
            {
                tabFormControl1.SelectedPage = pages;
                return true;
            }

            if (uiObj.Type == E_FunctionType.FT_DlgUI ||
                uiObj.Type == E_FunctionType.FT_FormUI)
            {
                //依对话框的形式显示
                return OnShowWithForm(uiObj);
            }

            var page = OnCreateTab(uiObj);
            if (page != null)
            {
                tabFormControl1.SelectedPage = page;
                return true;
            }
            return false;
        }

        /// <summary>
        /// 关闭特定的UI对象
        /// </summary>
        /// <param name="ui"></param>
        public void CloseUi(KUIObject ui)
        {
            if (ui == null)
                return;
            var tab = OnGetTab(ui.Name);
            if (tab == null)
                return;
            tabFormControl1.ClosePage(tab);
        }


        /// <summary>
        /// 获得当前页面已经打开的Tab
        /// </summary>
        /// <param name="strName"></param>
        /// <returns></returns>
        private TabFormPage OnGetTab(string strName)
        {
            return tabFormControl1.Pages.FirstOrDefault((a) =>
            {
                var ui = a.Tag as IUIObject;
                if (ui == null)
                    return false;
                return ui.UIObject.Name == strName;
            });
        }

        /// <summary>
        /// 创建添加Tab功能对象
        /// </summary>
        /// <param name="uiInfo"></param>
        private TabFormPage OnCreateTab(KUIObject uiInfo)
        {
            try
            {
                if (uiInfo == null || string.IsNullOrEmpty(uiInfo.Name))
                    return null;
                IUIObject uiImpl = uiInfo.UICtrl;
                if (uiImpl == null)
                    return null;
                Control ctrl = uiImpl.GetOrCreateCtrl<Control>();
                if (ctrl == null || ctrl.IsDisposed)
                {
                    ctrl = uiImpl.ReCreateCtrl<Control>();
                    if (ctrl == null)
                        return null;
                }

                //兼容老版本的RibbonControl的功能
                if (uiImpl.GetAttr("CmdPages") is RibbonControl cmdPages)
                {
                    //将RibbonPage设置为只有按钮显示的效果
                    cmdPages.ShowToolbarCustomizeItem = false;
                    cmdPages.ShowApplicationButton = DefaultBoolean.False;
                    cmdPages.ShowExpandCollapseButton = DefaultBoolean.False;
                    cmdPages.ShowPageHeadersMode = ShowPageHeadersMode.Hide;
                    cmdPages.ToolbarLocation = RibbonQuickAccessToolbarLocation.Hidden;
                }
                var tabPage = new TabFormPage()
                {
                    Name = uiInfo.Name,
                    Tag = uiImpl,
                    Text = string.IsNullOrEmpty(uiInfo.Title) ? uiInfo.Desc : uiInfo.Title
                };
                var image = uiInfo.Image;
                if (image != null)
                    tabPage.Image = ImageResObject.ReduceImage(image, 16, 16);

                ctrl.Dock = DockStyle.Fill;
                tabPage.ContentContainer = new TabFormContentContainer() { Dock = DockStyle.Fill };
                tabPage.ContentContainer.Controls.Add(ctrl);

                this.tabFormControl1.Pages.Add(tabPage);
                return tabPage;
            }
            catch (Exception e)
            {
                KApplication.ErrorDebug(e.Message);
                KApplication.ErrorLog(e.Message);
                return null;
            }
        }



        /// <summary>
        /// 依显示框的显示显示
        /// </summary>
        /// <param name="uiObj"></param>
        /// <returns></returns>
        private bool OnShowWithForm(KUIObject uiObj)
        {
            var uiImpl = uiObj.UICtrl;
            if (uiImpl == null)
                return false;
            Control uiCtrl = uiImpl.GetOrCreateCtrl<Control>();
            if (uiCtrl == null)
                throw new Exception("系统异常:未获得组件实现!");
            Form mainForm = null;
            if (uiCtrl is Form form)
                mainForm = form;
            else
            {
                //返回的是控件对象
                if (uiCtrl.IsDisposed)
                {
                    //考虑重建(框架7支持)
                    uiCtrl = uiImpl.ReCreateCtrl<Control>();
                    if (uiCtrl == null)
                        throw new Exception("系统异常:未获得组件实现!");
                }
                uiCtrl.Dock = DockStyle.Fill;
                mainForm = new XtraForm
                {
                    StartPosition = FormStartPosition.CenterScreen,
                    Icon = System.Drawing.Icon.ExtractAssociatedIcon(Application.ExecutablePath),
                    Height = uiCtrl.Height + 20,
                    Width = uiCtrl.Width + 20,
                    Text = string.IsNullOrEmpty(uiObj.Title) ? uiObj.Desc : uiObj.Title,
                    WindowState = FormWindowState.Normal
                };
                mainForm.Closed += delegate (object sender, EventArgs args)
                {
                    if (!uiObj.IsCreateAlways)
                        mainForm.Controls.Remove(uiCtrl);
                    else
                        uiImpl.ExitInitstance();//释放对象,准备下次重建
                    mainForm.Dispose();
                };
                mainForm.Controls.Add(uiCtrl); ;
            }
            if (uiObj.Type == E_FunctionType.FT_MdiUI)
            {
                if (mainForm.Width < 150)
                    mainForm.WindowState = FormWindowState.Maximized;
                mainForm.Show();
                return true;
            }
            return mainForm.ShowDialog() == DialogResult.OK;
        }
        #endregion


    }
}
